package com.leesche.zcsp.node.utils.web;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by kaider on 2016/9/21.
 */
public class BeanDescribe
{
    private Object beanInstance;

    /**
     * <p>Constructor for BeanDescribe.</p>
     *
     * @param beanInstance a {@link java.lang.Object} object.
     */
    public BeanDescribe(Object beanInstance)
    {
        this.beanInstance = beanInstance;
    }

    /**
     * <p>describe.</p>
     *
     * @return a {@link java.util.Map} object.
     */
    public Map<String, Object> describe()
    {
        Map<String, Object> results = new HashMap<String, Object>();

        if(beanInstance == null){
            return results;
        }

        try
        {
            BeanInfo beanInfo = Introspector.getBeanInfo(beanInstance.getClass());

            PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();

            for (PropertyDescriptor descriptor : descriptors)
            {
                results.put(
                        descriptor.getName(),
                        descriptor.getReadMethod().invoke(beanInstance)
                );
            }

            return results;
        }
        catch (Exception e)
        {
            throw new IllegalStateException(e);
        }

    }
}
